package com.sz.biz.common.customer.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sz.biz.common.customer.service.CustomerMenuService;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.service.role.MembershipType;
import com.sz.common.core.service.role.RoleMembership;
import com.sz.common.core.system.dto.MenuItem;
import com.sz.common.core.system.dto.PermissionDto;
import com.sz.common.core.system.entity.Authorization;
import com.sz.common.core.system.entity.Role;
import com.sz.common.core.system.service.AuthorizationService;
import com.sz.common.core.system.service.MenuService;
import com.sz.common.core.system.service.RoleService;

/**
 * 
 * Function: TODO: ADD FUNCTION <br>
 * Author: qiankun <br>
 * Date: 2017-05-24 11:17:16
 */
@Service("CustomerMenuService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CustomerMenuServiceImpl implements CustomerMenuService {

	@Autowired
	private RoleService roleService;

	@Autowired
	private MenuService menuService;

	@Autowired
	private AuthorizationService authorizationService;

	@Override
	public MenuItem getMenuAndPermissionTree(Integer userId) {
		String localLanguage = PrincipalUtils.getLocalLanguage();
		int domainId = PrincipalUtils.getDomainId();
		int roleId = PrincipalUtils.getRoleIds().get(0);
		//获取到当前用户的权限菜单
		MenuItem root = menuService.getMenuTree(domainId, localLanguage, false, false);
		// 根据roleId集合获取相应的menuId
		List<Authorization> authorizationList = authorizationService.findAuthListByRoleIds(Arrays.asList(roleId), 1);// 1代表菜单
		List<Integer> authorizedMenuIdList = new ArrayList<>();
		authorizationList.forEach(authorization -> authorizedMenuIdList.add(authorization.getResId()));
		List<Authorization> authorizationPermissionList = authorizationService
				.findAuthListByRoleIds(Arrays.asList(roleId), 2);// 2代表权限
		removeUnauthorizedMenuAndAddPermission(root, authorizedMenuIdList, false, authorizationPermissionList);
        //拿到目前用户地下的可以分配的用户
		RoleMembership roleSubMembership = new RoleMembership(userId, MembershipType.CUSTOMER);
		List<Role> subRoleList = roleService.getRoleByMember(roleSubMembership);
		if(subRoleList == null || subRoleList.size()==0){
			return root;
		}
		int subRoleId=subRoleList.get(0).getId();
		List<Authorization> subAuthorizationList = authorizationService.findAuthListByRoleIds(Arrays.asList(subRoleId), 1);// 1代表菜单
		List<Integer> subAuthorizedMenuIdList = new ArrayList<>();
		subAuthorizationList.forEach(authorization -> subAuthorizedMenuIdList.add(authorization.getResId()));
		List<Authorization> subAuthorizationPermissionList = authorizationService
				.findAuthListByRoleIds(Arrays.asList(subRoleId), 2);// 2代表权限
	    removeUnauthorizedMenuAndPermission(root, subAuthorizedMenuIdList, false, subAuthorizationPermissionList);
		return root;
	}
	
	private boolean removeUnauthorizedMenuAndPermission(MenuItem item, List<Integer> permittedMenuIds, Boolean isRemove,
			List<Authorization> authorizationPermissionList){
		  if (permittedMenuIds.contains(item.getId())) {
	            for (Authorization authorization : authorizationPermissionList) {
	                if (authorization.getResId().equals(item.getId())) {
	                    List<PermissionDto> list = item.getPermissions();
	                    if (!list.isEmpty()) {
	                        list.forEach(obj -> {
	                            if (authorization.getPermissionId().equals(obj.getId())) {
	                                obj.setSelected(true);
	                            }
	                        });
	                    }
	                }
	            }
	            return true;
	        }
	        boolean keepChild = false;
	        if (item.hasChild()) {
	            for (MenuItem childItem : item.getChildren()) {
	                if (removeUnauthorizedMenuAndPermission(childItem, permittedMenuIds, isRemove, authorizationPermissionList)) {
	                    keepChild = true;
	                    childItem.setSelected(true);
	                    item.setSelected(true);
	                } else {
	                    childItem.setSelected(false);
	                }
	            }
	        }
	        return keepChild;
	}

	private boolean removeUnauthorizedMenuAndAddPermission(MenuItem item, List<Integer> permittedMenuIds, Boolean isRemove,
			List<Authorization> authorizationPermissionList) {
		if (permittedMenuIds.contains(item.getId())) {
			 List<PermissionDto> permissionDtos = new ArrayList<>();
			for (Authorization authorization : authorizationPermissionList) {
				if (authorization.getResId().equals(item.getId())) {
                    PermissionDto pdto = new PermissionDto();
                    BeanUtils.copyProperties(authorization, pdto);
                    pdto.setMenuId(item.getId());
                    permissionDtos.add(pdto);
				}
			}
			item.setPermissions(permissionDtos);
			return true;
		}
		item.setSelected(false);
		boolean keepChild = false;
		if (item.hasChild()) {
			Iterator<MenuItem> it = item.getChildren().iterator();
			while (it.hasNext()) {
				MenuItem childItem = it.next();
				if (removeUnauthorizedMenuAndPermission(childItem, permittedMenuIds, isRemove,
						authorizationPermissionList)) {
					keepChild = true;
					childItem.setSelected(false);
				} else {
					it.remove();
				}
			}
		}
		return keepChild;
	}

	
}
